//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj登录

#import "LoginViewController.h"
#import "LanguageController.h"
#import "CountryCodeVC.h"
#import "RegisterViewController.h"
#import "AllCountryCodeVC.h"
#import "NBPhoneNumberUtil.h"
#import "EnterCodeController.h"
#import "CaptchaView.h"
#import "MJConfirmLoadingView.h"
#import "EmailCodeVC.h"
#import "LoginPasswordVC.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UILabel *countryCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet MJUITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet MJConfirmLoadingView *confirmButton;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberBgView;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)mj_setUI{
    [super mj_setUI];
    
    [self.navigationController setNavigationBarHidden:true animated:NO];

//    NSDictionary *data = @{@"userId":@"23423423423"};
//    [UserManager.shared saveUserInfo:data];
    
    self.phoneNumberTextField.mj_disableThirdPartyKeyboard = true;
    self.phoneNumberTextField.font = MJUIFontMake(20);
    
    self.tipLabel.hidden = true;
    self.countryCodeLabel.text = @"";

//    self.countryAreaCode = [HealthHelper getCountryAreaCode];
    if(self.countryAreaCode){
        
    }else{
        self.countryAreaCode = [HealthHelper getCountryAreaCode];
    }
    
    NSString *code = [NSString stringWithFormat:@"+%@",self.countryAreaCode[@"区号"]];
    self.countryCodeLabel.text = code;
    
    if([self.countryCodeLabel.text containsString:@"+86"]){
        self.phoneNumberTextField.mj_limitedNumber = 11;
    }
    
    if(self.phoneNumber.length){
        self.phoneNumberTextField.text = self.phoneNumber;
    }else{
        [self.phoneNumberTextField mj_becomeFirstResponder];
    }
    
    NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
    MJWeakSelf
    RAC(self.confirmButton, enabled) = [RACSignal combineLatest:@[self.phoneNumberTextField.rac_textSignal] reduce:^id _Nullable(NSString * text){
        
        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(text.length == 11 && [text mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:text
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
      
        if(enable){
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_appColor width:2];
        }else{
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
            weakSelf.tipLabel.hidden = true;
        }
        return @(enable);
    }];
 
    self.confirmButton.handleContinueBlock = ^{
        [weakSelf handleConfirmButtonClick];

    };
//    [self mj_pushViewController:@"EnterCodeController"];
//    [self handleCountryCodeButtonClick:nil];
//    [self sendAnjCcaptchaCode];
}

#pragma mark - 方法
- (void)requestData{
    
}

- (IBAction)handleEmailCodeButtonClick:(UIButton *)sender {
    
    if([self.navigationController mj_containTargetVCWithClass:EmailCodeVC.class]){
        [self.navigationController mj_popViewControllerWithTargetClass:EmailCodeVC.class];
    }else{
        EmailCodeVC *vc = [[EmailCodeVC alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
}

- (IBAction)handlePasswordButtonClick:(UIButton *)sender {
    LoginPasswordVC *loginVC = [[LoginPasswordVC alloc]init];
    BasicNavigationController * nav = [[BasicNavigationController alloc]initWithRootViewController:loginVC];
    AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    appDelegate.window.rootViewController = nav;
}

- (IBAction)handleLanguageButtonClick:(UIButton *)sender {
    LanguageController *vc = [[LanguageController alloc]init];
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleRegisterButtonClick:(UIButton *)sender {
    RegisterViewController *vc = [[RegisterViewController alloc]init];
    vc.countryAreaCode = self.countryAreaCode;
    [self.navigationController pushViewController:vc animated:true];
}

- (IBAction)handleCountryCodeButtonClick:(UIButton *)sender {
    MJWeakSelf
    AllCountryCodeVC *vc = [[AllCountryCodeVC alloc]init];
    vc.handleCountryCodeBlock = ^(NSDictionary *countryAreaCode) {
        NSString *code = [NSString stringWithFormat:@"+%@",countryAreaCode[@"区号"]];
        weakSelf.countryCodeLabel.text = code;
        weakSelf.countryAreaCode = countryAreaCode;

    };
    [self.navigationController pushViewController:vc animated:true];
}

- (void)handleConfirmButtonClick {
    [self.phoneNumberTextField resignFirstResponder];

    NSDictionary *params =  @{
        @"countryCode": self.countryAreaCode[@"区号"],
        @"phoneNumber": self.phoneNumberTextField.text,
        @"region": self.countryAreaCode[@"ISO"],
    };
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:params requestUri:user_findByPhone requestType:RequestTypeGet showLoading:false success:^(MJBaseModel *model) {
        
        [weakSelf.confirmButton.loadingView stopAnimation];
        if(model.code == 200){
//            weakSelf.tipLabel.hidden = false;
//            return;
            weakSelf.tipLabel.hidden = true;

            if(model.data){
                MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
                configure.confirmButtonColor = UIColor.mj_appColor;
                configure.confirmTitle = MJUILocalizedString(@"OK_qd");
                configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
                configure.messageAlignmentCenter = true;
                NSString *phone = [NSString stringWithFormat:@"+%@%@",self.countryAreaCode[@"区号"],self.phoneNumberTextField.text];
                NSString *messageString = [[MJUILocalizedString(@"We will send a verification code to the following number:") stringByAppendingString:@"\n"] stringByAppendingString:phone];
                [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Mobile Number Confirmation") message:messageString configure:configure confirmBlock:^{
                    
                    [weakSelf sendAnjCcaptchaCode];
                    
                } cancelBlock:^{

                }];
            }else{
                //未注册
                MJUIAlertViewConfigure *configure = [[MJUIAlertViewConfigure alloc]init];
                configure.confirmButtonColor = UIColor.mj_appColor;
                configure.confirmTitle = MJUILocalizedString(@"OK_qd");
                configure.cancelTitle = MJUILocalizedString(@"Cancel_qx");
                configure.messageAlignmentCenter = true;
                NSString *messageString = MJUILocalizedString(@"The number is not registered. Sign up for a new account now?");
                [MJUIAlertView alertViewWithTitle:MJUILocalizedString(@"Phone Number Not Registered") message:messageString configure:configure confirmBlock:^{
                    RegisterViewController *vc = [[RegisterViewController alloc]init];
                    vc.phoneNumber = weakSelf.phoneNumberTextField.text;
                    vc.countryAreaCode = weakSelf.countryAreaCode;
                    [weakSelf.navigationController pushViewController:vc animated:true];
                } cancelBlock:^{

                }];
            }
        }else if(model.code == 417){
            weakSelf.tipLabel.hidden = false;
        }

    } failure:^(NSError *error) {
        [weakSelf.confirmButton.loadingView stopAnimation];

    }];

}

/// 滑块验证码
- (void)sendAnjCcaptchaCode {
    
    MJWeakSelf
    [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
        
        [weakSelf.confirmButton.loadingView startAnimation];

        NSLog(@"result=======================%@",result);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
            @"countryCode": self.countryAreaCode[@"区号"],
            @"phoneNumber": self.phoneNumberTextField.text,
            @"region": self.countryAreaCode[@"ISO"],
            @"code": result,
        }];
        [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendSms requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
            [weakSelf.confirmButton.loadingView stopAnimation];

            if (model.code ==  200){
                
                EnterCodeController *vc = [[EnterCodeController alloc]init];
                vc.captchaCodeType = CaptchaCodeTypeLogin;
                vc.phone = weakSelf.phoneNumberTextField.text;
                vc.countryAreaCode = weakSelf.countryAreaCode;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }else if(model.code ==  412){
                [RoyHud showToast:MJUILocalizedString(@"Too frequent, Retry later.")];
            }
            
        } failure:^(NSError *error) {
            [weakSelf.confirmButton.loadingView stopAnimation];

        }];
    }];
}

#pragma mark - 代理

#pragma mark - 懒加载

@end
